﻿using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GT.Framework.RabbitMQ.Core
{
    /// <summary>
    /// 接收消息
    /// </summary>
    public class DoRabbitMQSubscribe: DoRabbitMQBase
    {
        public string QueueName { get; private set; }

        public DoRabbitMQSubscribe(string queueName)
        {
            QueueName = queueName;
            // 创建一个消息队列
            //exchange type: fanout,direct,topic,headers
            //fanout:广播,消息后会将消息广播给所有绑定到它上面的队列
            Channel.ExchangeDeclare(exchange: "", type: "direct", durable: true, autoDelete: false, arguments: null);

            //durable:持久化
            //exclusive:程序退出后被自动删除
            Channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
            //channel.BasicQos();

            //channel.ExchangeBind("", "", "");
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        public void Subscribe(string message) {
            var consumer = new EventingBasicConsumer(Channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                //var message = Encoding.UTF8.GetString(body);

                //var message = body.Deserialize<MQMessage>();

                //Trace.WriteLine(string.Format("ID:{0},Name:{1},CreateTime:{2}", message.ID, message.Name, message.CreateTime.ToString("yyyy-MM-dd HH:mm:ss fff")));
            };

            Channel.BasicConsume(queue: QueueName, noAck: true, consumerTag: "", noLocal: true, exclusive:true, arguments: null, consumer: consumer);
        }


    }
}
